<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<!-- script type="text/javascript" src="../myext/PersonListGridPanel.js"></script> -->
<script type="text/javascript">
	Ext.onReady(function(){
		Ext.QuickTips.init();	//初始化Ext.QuickTips，以使得tip提示可用
		Ext.form.Field.prototype.msgTarget='side';		//提示后面显示图片标记
		/**
		 * JS中，当有对象需要引用的时候，必须在引用之前就定义，否则的话，需要在constructor中初始化
		 */
		DataDictInfoFormPanel = Ext.extend(Ext.form.FormPanel,{
			constructor:function(){
				DataDictInfoFormPanel.superclass.constructor.call(this,{
					labelWidth:100,
					defaults:{anchor:'90%'},		//自动拉伸
					baseCls:'x-plain',			//强制设置窗体颜色
					defaultType:'textfield',
					bodyStyle:'padding:8px',
					items:[{
						xtype:'hidden',
						name:'id'
					},{
						fieldLabel:'工号',
						allowBlank:false,
						name:'userId',
						maxLength:50
					},{
						fieldLabel:'部门',
						name:'deptName'
					},{
						fieldLabel:'姓名',
						name:'username'
					},{
						fieldLabel:'登记号码',
						name:'singNum'
					},{
						fieldLabel:'上班时间_上午',
						name:'workTimeAm'
					},{
						fieldLabel:'上班时间_下午',
						name:'workTimePm'
					},{
						fieldLabel:'记录状态',
						name:'state'
					},{
						fieldLabel:'机器号',
						name:'machineNum'
					},{
						fieldLabel:'工种代码',
						name:'workCode'
					},{
						fieldLabel:'比对方式',
						name:'comparison'
					}]
				})
			},
			getValues:function(){
				//alert(Ext.util.JSON.encode(this.form.getValues()));
				if(this.getForm().isValid()){
					this.fireEvent("submit",this,this.form.getValues());
				}else{
					throw Error("表单验证未通过！");		//抛出异常，在调用getValues函数的地方捕获并提示
				}
				//alert(this.getForm().getValues());
				return new Ext.data.Record(this.getForm().getValues());
			},
			setValues:function(re){
				this.getForm().loadRecord(re);
			},
			reset:function(){
				this.getForm().reset();
			}
		});
		
		UploadFileForm = Ext.extend(Ext.form.FormPanel,{
			constructor:function(){
				UploadFileForm.superclass.constructor.call(this,{
			        fileUpload: true,
			        width: 500,
			        frame: true,
			      //  title: 'File Upload Form',
			        autoHeight: true,
			        bodyStyle: 'padding: 10px 10px 0 10px;',
			        labelWidth: 50,
			        defaults: {
			            anchor: '95%',
			            allowBlank: false,
			            msgTarget: 'side'
			        },
			        items: [{
			            xtype: 'fileuploadfield',
			            id: 'form-file',
			           // emptyText: 'Select an image',
			            fieldLabel: 'Excel',
			            name: 'upload'
			        }]
			    })
			}
		});
		
		UploadFileWindow = Ext.extend(Ext.Window,{
			uploadform:null,
			constructor:function(){
			this.uploadform = new UploadFileForm(),
				UploadFileWindow.superclass.constructor.call(this,{
					id:'upwindow',
					title:'上传Excel',
					plain:true,			//通过背景颜色来渲染窗口颜色
					items:this.uploadform,
					modal:true,			//只能操作当前窗口
					closeAction:'hide',
					buttons:[{
						text:'确定',
						handler:this.onUploadsubmit,
						scope:this
					},{
						text:'取消',
						handler:this.onUploadcanel,
						scope:this
					}]
				});
			},
			close:function(){
				Ext.getCmp('form-file').setValue('');//this.uploadform.reset();
				this.hide();
			},
			onUploadcanel:function(){
				this.close();
			},
			onUploadsubmit:function(){
				var fileVal = Ext.getCmp('form-file').getValue();
				var fileArr = fileVal.split('.')[1];
				
				if(this.uploadform.getForm().isValid()&&(fileArr == "xls"||fileArr=="xlsx")){
					this.uploadform.getForm().submit({
						url: 'uploadexc.action',
						//waitMsg: 'Uploading your photo...',
						success: function(response){
// 							alert(response.responseText);
// 							alert(123);
						    //msg('Success', 'Processed file "'+o.result.file+'" on the server');
						},
						failure:function(response){
							//上传完后,返回失败,
							Ext.getCmp('upwindow').hide();
							Ext.getCmp('userWorkTimeGrid').getStore().reload();
						}
					
             		});
	        	}else{
	        		Ext.Msg.alert('提示','请选择Excel文件!');
	        	}
				//
			}
		});
		/**
		 * 弹出编辑窗口类，提供创建和修改使用
		 */
		 WorkTimeInfoWindow = Ext.extend(Ext.Window,{
			//将FormPanel放到Window中
			form:null,
			constructor:function(){
				this.form = new DataDictInfoFormPanel(),
				WorkTimeInfoWindow.superclass.constructor.call(this,{
					
					plain:true,			//通过背景颜色来渲染窗口颜色
					width:500,
					modal:true,			//只能操作当前窗口
					closeAction:'hide',
					items:this.form,
					buttons:[{
							text:'确定',
							handler:this.onsubmit,
							scope:this
						},{
							text:'取消',
							handler:this.oncanel,
							scope:this
						}]
				});
				this.addEvents("submit");
			},	
			close:function(){
				this.form.reset();
				this.hide();
			},
			//workTime提交只有更新和删除
			onsubmit:function(){
				try{
					this.fireEvent("submit",this,this.form.getValues());
					//获得Form提交后的ID,如果为空,表示添加,否则为修改
 					var id = Ext.util.JSON.encode(this.form.getValues().data.id);
					
					Ext.Ajax.request({
						url:'',
						params:{
							content:"["+Ext.util.JSON.encode(this.form.getValues().data)+"]"
						},
						//提交成功后,处理一些事务
						 success : function(response){
							//alert(response.responseText);
							var value = Ext.util.JSON.decode(response.responseText);
							var cc =new Ext.data.Record.create(['id','itemId','dictName','value1','value2','remark','parentId']);
							var cdata = new cc(value.dataDict);
							//将数据插入到第一行,并删除store最后一行
							var gridStore = Ext.getCmp('dataDictGrid').store;
							var c = id.replace('"','').replace('"','');		//去除不必要的符号
							if(""==c){
								if(gridStore.getCount() == 20){
									gridStore.insert(0,cdata);
									gridStore.remove(gridStore.getAt(gridStore.getCount()-1));
								}else{
									//gridStore.add(cdata);
									gridStore.insert(0,cdata);
								}
							}else{
								var selectRe = Ext.getCmp('dataDictGrid').getSelectionModel().getSelected();			//获得Grid选择的record
								var data = selectRe.data;
								//alert(Ext.util.JSON.encode(data));		//获得Record的数据，然后转换成JSON打印
								//遍历record.data,修改原record的值
								for(var i in data){
									selectRe.set(i,cdata.get(i));
								}
								selectRe.commit();
							}
						}  
					});
				}catch(err){
					Ext.Msg.alert('提示',err);
					return ;
				}
				this.close();
			},
			oncanel:function(){
				this.close();
			}
		}) ;

		/*********************************/
		//添加
		InsertWorkTimeInfoWindow = Ext.extend(WorkTimeInfoWindow,{
			title:'添加数据'
		});
		//修改
		UpdateWorkTimeInfoWindow = Ext.extend(WorkTimeInfoWindow,{
			title:'修改数据',
			load:function(re){
				this.form.setValues(re);
			}
		});
		/**
		 * 数据显示Grid
		 */
		 WorkTimeInfoGrid = Ext.extend(Ext.grid.GridPanel,{
			fileUploadWin:new UploadFileWindow(),	
			insertWorkTimeWin:new InsertWorkTimeInfoWindow(),
			updateWorkTimeWin:new UpdateWorkTimeInfoWindow(),
			constructor:function(){
				this['store']= new Ext.data.JsonStore({
					root:'list',
					totalProperty:'cnt',
					url:'findallworktime.action',
				fields:[{
							name:'id', type: 'int'
						},'userId','deptName','username','singNum','workTimeAm','workTimePm','state','machineNum','workCode','comparison','worktimeState']
				}),

				this['twoTbar'] = new Ext.Toolbar( {
					height : 30,
					items : ["查询：", "-", "姓名：", {
						id : 'txtEName',
						xtype : "textfield",
						width : 100
					},
					 {
						text : '查询',
						icon:'imgs/zoom/zoom.png',
						iconCls : 'onSearch',
						handler : function() {
							//查询参数赋值
						
							//systemUsersGrid.store.baseParams['queryLock'] = true;
							
							//systemUsersGrid.store.baseParams['userName'] = txtEName.value;//防止分页时丢失
							//systemUsersGrid.store.reload();
						}
					},{
						text : '上传Excel',
						icon:'imgs/page/page_excel.png',
						iconCls : 'onSearch',
						handler : function() {
							this.fileUploadWin.show();
						},
						scope:this
					}

					]
				}),
				  
				//ToolBar
				this['toolBar'] = new Ext.Toolbar({
					
					items:[
// 					       {
// 						text:'新增',
// 						icon:'../../imgs/add.gif',
// 						cls: "x-btn-text-icon" ,		//自定义图片
// 						handler:function(){
// 							this.insertWorkTimeWin.show();
// 						},
// 						scope:this
// 					},"-",
					{
						text:'修改',
						icon:'imgs/edit.gif',
						cls: "x-btn-text-icon" ,		//自定义图片
						handler:function(){
							this.updateWorkTimeWin.show();						//首先,修改窗体显示
							try{											//然后将用户选择的数据回写到窗体上	
								this.updateWorkTimeWin.load(this.getSelected());
							}catch(err){
								Ext.Msg.alert('提示',err.description);
								this.updateWorkTimeWin.close();
							}
						},
						scope:this
					},"-",{
						text:'删除',
						icon:'imgs/delete.gif',
						cls: "x-btn-text-icon" ,		//自定义图片
						handler:function(){
							this.onRemove()	
						},
						scope:this
					}]
				})
				WorkTimeInfoGrid.superclass.constructor.call(this,{
					id:'userWorkTimeGrid',
					title:'用户打卡时间表',
					renderTo:'userWorkTimeGrid',
					height : Ext.get('userWorkTimeGrid').getHeight(), 
					autoExpandColumn:10,
					//height : Ext.get('dataDictGrid').getHeight(), 
					sm:new Ext.grid.RowSelectionModel({
						singleSelect:true
					}),
					tbar:this.toolBar,
					listeners : {

						'render' : function() {
							this.twoTbar.render(this.tbar);
						}

					},
					bbar:new Ext.PagingToolbar({
						pageSize:20,
						store:this.store,
						displayInfo:true,
						displayMsg:'第{0}条到{1}条，共{2}条',
						emptyMsg:'没有记录'
					}),
					columns:[
					         //new Ext.grid.RowNumberer(),//自动行号
								{
									header:'工号',
									width:100,
									dataIndex:'userId',
									sortable:true
								},{
									header:'部门',
									width:100,
									dataIndex:'deptName',
									sortable:true
								},{
									header:'姓名',
									width:100,
									dataIndex:'username',
									sortable:true
								},{
									header:'登记号码',
									width:100,
									dataIndex:'singNum',
									sortable:true
								},{
									header:'上班时间_上午',
									width:300,
									dataIndex:'workTimeAm',
									sortable:true
								},{
									header:'上班时间_下午',
									width:300,
									dataIndex:'workTimePm',
									sortable:true
								},{
									header:'记录状态',
									width:100,
									dataIndex:'state',
									sortable:true
								},{
									header:'机器号',
									width:100,
									dataIndex:'machineNum',
									sortable:true
								},{
									header:'工种代码',
									width:100,
									dataIndex:'workCode',
									sortable:true
								},{
									header:'比对方式',
									width:100,
									dataIndex:'comparison',
									sortable:true
								},{
									header:'打卡状态',
									dataIndex:'worktimeState',
									sortable:true,
									renderer:function(value){
										if(value == '1'){
											return String.format(
											　　　　　　　　　'<input id="show" type="image" src="../imgs/feed_error.png" title="迟到" />'
											　　　　　　　　　　　　　　 );
										}else if (value == '2'){
											return String.format(
											　　　　　　　　　'<input id="show" type="image" src="../imgs/warning.gif" title="早退" />'
											　　　　　　　　　　　　　　 );
										}else if(value == '3'){
											return String.format(
											　　　　　　　　　'<input id="show" type="image" src="../imgs/cross.gif" title="打卡异常" />'
											　　　　　　　　　　　　　　 );	
										}else {
											return String.format(
											　　　　　　　　　'<input id="show" type="image" src="../imgs/checked.gif" title="正常" onclick="alert(\'正常\')"/>'
											　　　　　　　　　　　　　　 );
										}	
										
									}
								}]
				});
				this.getStore().load({
					url:'findallworktime.action',
					params:{start:0,limit:20}
				});
				//this.insertDataDict.on('submit',this.onsubmit,this);		//为可视化窗口:insertWin添加事件(事件名称，调用的函数，scope)
			Ext.Ajax.on('requestcomplete',this.requestFunction,this);
		},
		//判断用户是否选择了数据
		getSelected:function(){
			var sm = this.getSelectionModel();
			if(sm.getCount() == 0){
				throw Error('需要选择一条数据');
			}
			return sm.getSelected();	
			
		},
		//删除数据
		onRemove:function(){
			var sm = this.getSelectionModel();
			if(sm.getCount() == 0){
				Ext.Msg.alert('提示','需要选择一条数据');
			}else{
				Ext.Msg.confirm('提示','是否删除？',function(btn, text){
					//Ext.Msg.confirm('提示','是否删除？',this.onRemove,this);
					if(btn == 'yes'){
						try{
							var store = this.store;
							var selectRe = this.getSelected();			//获得Grid选择的record
							
							store.remove(selectRe);
							alert(selectRe.get('id'));
							Ext.Ajax.request({
								url:'',
								params:{
									'dataDict.id':selectRe.get('id')
								},
								success : function(response){
									//alert(response.responseText);
									store.load({
											params:{start:0,limit:20}
										});
								}  
								
							});	//修改时，form联动
						}catch(err){
							Ext.Msg.alert('提示','需要选择一条数据');
						}
						//删除后,直接刷新
						
					}
				},this);
			}
		},
		insert:function(re){
			alert(11111);
			//alert(this.title);
			//此处的this为GridPanel
			this.getStore().add(re);	
		},
		update:function(re){
			try{
				var selectRe = this.getSelected();			//获得Grid选择的record
				var data = selectRe.data;
				//alert(Ext.util.JSON.encode(data));		//获得Record的数据，然后转换成JSON打印
				//遍历record.data,修改原record的值
				for(var i in data){
					//alert(i);
					selectRe.set(i,re.get(i));
					
				}
				selectRe.commit();
				this.fireEvent("rowselect", selectRe);		//修改时，form联动
				
			}catch(err){
				throw Error('需要选择一条数据');
			}
		},
		//在插入数据的时候,返回的ID需要重新加载到insertdata对象中,这样就同数据库一样了,根据ID可以修改和删除数据
		requestFunction:function(conn,response,options){
// 			var c = Ext.util.JSON.decode(response.responseText);
// 			alert(response.responseText)
// 			var res = c.list;
// 			for(var i = 0;i<res.length;i++){
// 				var rc = res[i];
// 			}
		}
		});
		new WorkTimeInfoGrid();
	});
</script>
<title>员工打卡统计</title>
</head>
<body>
<div id="userWorkTimeGrid"  style="width:100%; height:100%" ></div>
</body>
</html>